#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> // Added for close() and sleep()
#include <errno.h>  // Added for perror

#define PORT 8888 // Should match server port

int main(int argc, char **argv)
{
    int sock;
    struct sockaddr_in server_addr; // Renamed for clarity
    socklen_t len;                  // Often needed for getsockname/getpeername, though not used here
    char buf[100];
    char recbuf[100];

    // Argument check should be for IP address and the number to send
    if (argc < 3)
    {
        // Corrected usage message
        printf("Usage: %s <server_ip> <number_to_send>\n", argv[0]);
        exit(1);
    }

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket create error!");
        exit(1);
    }

    memset(&server_addr, 0, sizeof(server_addr)); // Good practice to zero out struct
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT); // Use the defined PORT

    // Use argv[1] for IP address
    if (inet_aton(argv[1], &server_addr.sin_addr) == 0)
    {                                                                // Use server_addr.sin_addr directly
        fprintf(stderr, "Invalid server IP address: %s\n", argv[1]); // Use fprintf for errors
        close(sock);
        exit(1);
    }

    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0)
    { // Use sizeof(struct sockaddr_in)
        perror("connect error!");
        close(sock);
        exit(1);
    }

    printf("connected!\n");

    // Use argv[2] for the data to send
    strncpy(buf, argv[2], sizeof(buf) - 1);
    buf[sizeof(buf) - 1] = '\0'; // Ensure null termination

    // Send the data from argv[2]
    ssize_t sent_len = send(sock, buf, strlen(buf), 0); // Send the whole string

    if (sent_len < 0)
    {
        perror("send error!");
        close(sock);
        exit(1);
    }
    else if (sent_len < strlen(buf))
    {
        fprintf(stderr, "Warning: Partial send\n");
        // Handle partial send if necessary
    }

    ssize_t recv_len = recv(sock, recbuf, sizeof(recbuf) - 1, 0);
    if (recv_len < 0)
    {
        perror("recv error!");
        close(sock);
        exit(1);
    }
    else if (recv_len == 0)
    {
        printf("Server closed connection before sending response.\n");
    }
    else
    {
        recbuf[recv_len] = '\0'; // Null-terminate received data
        printf("the received data from server is %s\n", recbuf);
    }

    close(sock);
    return 0;
}